package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.itheima.MemberService;
import com.itheima.ReportDataService;
import com.itheima.ReportService;
import com.itheima.SetmealService;
import com.itheima.contant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.ChooseDateVo;
import com.itheima.pojo.HotSetmealVCS;
import com.itheima.pojo.ReportDataVCS;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberSevice;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    @Reference
    private ReportDataService reportDataService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Calendar calendar = Calendar.getInstance();
        //过去的第12月
        calendar.add(Calendar.MONTH, -12);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            list.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("months", list);
        List<Integer> memberCount = memberSevice.getmemberCountByMonths(list);
        map.put("memberCount", memberCount);
        return Result.success("", map);

    }

    @RequestMapping("/getMemberReport1")
    public Result getMemberReport1(@RequestBody ChooseDateVo chooseDateVo) {
        Result result = memberSevice.getMemberReport1(chooseDateVo);
        return result;
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
//返回值的数据格式{
// setmealNames:[name,name,]
// setmealCount:{
// {name:"",value:}
// {name:"",value:}
// {name:"",value:}
// {name:"",value:}
//
// }
//
// }
        Result result = setmealService.getSetmealReport();
        return result;
    }


    @RequestMapping("/getMemberMFReport")
    public Result getMemberMFReport() {

        return memberSevice.getMemberMFReport();
    }




    @RequestMapping("/getAgeReport")
    public Result getAgeReport(){
        return memberSevice.getAgeReport();
    }


    //远程调用服务获取报表数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            ReportDataVCS reportData = reportDataService.queryReportData();
            return Result.success("",reportData);
        } catch (Exception e) {
            return Result.error("");
        }
    }

    /*导出统计报表*/
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            ReportDataVCS report = reportDataService.queryReportData();


            //    今日到诊数
            Integer todayVisitsNumber = report.getTodayVisitsNumber();
            //    日期
            String reportDate = report.getReportDate();
            //   今日新增会员数
            Integer todayNewMember = report.getTodayNewMember();
            //    本周到诊数
            Integer thisWeekVisitsNumber = report.getThisWeekVisitsNumber();


            //    本月新增会员数
            Integer thisMonthNewMember = report.getThisMonthNewMember();

            //    本周新增会员数
            Integer thisWeekNewMember = report.getThisWeekNewMember();
            //   总会员数
            Integer totalMember = report.getTotalMember();
            //    本月预约数
            Integer thisMonthOrderNumber = report.getThisMonthOrderNumber();

            //    本月到诊数
            Integer thisMonthVisitsNumber = report.getThisMonthVisitsNumber();

            //    今日预约数
            Integer todayOrderNumber = report.getTodayOrderNumber();

            //   本周预约数
            Integer thisWeekOrderNumber = report.getThisWeekOrderNumber();

            //    热卖套餐
            List<HotSetmealVCS> hotSetmeal = report.getHotSetmeal();

            //从请求中获取 Excel文件的绝对路径
            String temlateRealPath = request.getSession().getServletContext().
                    getRealPath("template") + File.separator + "report_template.xlsx";

            /*读入模版，生成 Excel对象*/
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));

            /*生成工作簿*/
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (HotSetmealVCS setmeal : hotSetmeal) {
                String name = setmeal.getName();
                Integer count = setmeal.getSetmeal_count();
                float proportion = setmeal.getProportion();
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(count);
                row.getCell(6).setCellValue(proportion);
            }

            /*通过输出流进行文件下载*/
            ServletOutputStream outputStream = response.getOutputStream();
            /*将查询结果导出到 excel*/
            response.setContentType("application/vnd.ms-excel");
            /*设置导出excel文件，并设置文件名为report.xlsx*/
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            /**/
            response.setHeader("content-Disposition", "attachment;filename=" +
                    java.net.URLEncoder.encode("逾期的订单数据","utf-8") + ".xls");

            workbook.write(outputStream);

            outputStream.flush();
            outputStream.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            return Result.error("", MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}